class UsersController < ApplicationController
  before_filter :require_superadmin, :except => [ :login, :create, :logout, :update, :edit ]

  def create
    @page_description = "Create new user"
    @user = User.new(params[:user])
    if @user.save
      if (@user.id == 1)
        flash[:notice] = "You may now login, #{@user.name}."
        redirect_to :action => :login
      else
        flash[:notice] = "User #{@user.name} added."
        redirect_to :action => :index
      end
    else
      flash[:notice] = "Failed to save #{@user.name}."
      redirect_to :index
    end
  end

  def edit
    if is_superadmin?
      @user = User.find(params[:id])
    else
      @user = User.find(@logged_in_user.id)
    end
    @page_description = @user.name
  end

  def update
    user = User.find(params[:id])

    if (params[:user][:password].length > 0)
      params[:user][:password] = user.encrypt_password(params[:user][:password])
    else
      params[:user].delete(:password)
    end

    if is_superadmin?
      if user.update_attributes(params[:user])
        flash[:notice] = "#{user.name} updated."
      else
        flash[:notice] = "Failed to update #{user.name}."
      end
      redirect_to :action => :index
    elsif (@logged_in_user.id == user.id)
      if user.update_attribute(:password, params[:user][:password])
        flash[:notice] = "Password changed."
      else
        flash[:notice] = "Failed to change password."
      end
      redirect_to :action => :edit, :id => @logged_in_user.id
    else # someone who is not a super admin tried to change the password of someone other than themselves
      redirect_to :controller => "characters", :action => :index
    end
  end

  def index
    @page_description = "Users"
    @users = User.find(:all, :order => "name")

    alphabet = ('a'..'z').to_a + ('0'..'9').to_a
    @suggested_password = (1 .. 10).collect{ |ignored|
      alphabet[rand(alphabet.size)]
    }.join
  end

  def login
    @page_description = "Login"

    if request.get?
      session[:logged_in_user_id] = nil
      @user = User.new
    else
      @user = User.new(params[:user])

      @logged_in_user = @user.try_to_login
      if @logged_in_user
        session[:logged_in_user_id] = @logged_in_user.id
        flash[:notice] = "Welcome, #{@logged_in_user.name}.\n"
        redirect_to :controller => "characters", :action => :index
      else
        flash[:notice] = "Incorrect login."
      end
    end
  end

  def logout
    session[:logged_in_user_id] = nil
    flash[:notice] = "You are no longer logged in."
    redirect_to :controller => "characters", :action => :index
  end

end
